package com.bigtotoro.shuiyincamera;

import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.annotation.MainThread;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;
import android.view.View;
import android.widget.FrameLayout;
import android.widget.Toast;

import com.bigtotoro.shuiyincamera.csj.TTAdManagerHolder;
import com.bigtotoro.shuiyincamera.csj.WeakHandler;
import com.bigtotoro.shuiyincamera.util.NetWorkUtils;
import com.bigtotoro.shuiyincamera.util.SharedPreferencesUtil;
import com.bigtotoro.shuiyincamera.util.StatusBarUtil;
import com.bytedance.sdk.openadsdk.AdSlot;
import com.bytedance.sdk.openadsdk.TTAdConstant;
import com.bytedance.sdk.openadsdk.TTAdNative;
import com.bytedance.sdk.openadsdk.TTAppDownloadListener;
import com.bytedance.sdk.openadsdk.TTSplashAd;
import com.umeng.analytics.MobclickAgent;

import static com.bigtotoro.shuiyincamera.Constant.CURRENT_CHANNEL;


public class SplashActivity extends AppCompatActivity implements WeakHandler.IHandler {
    private static final String TAG = "SplashActivity";
    private TTAdNative mTTAdNative;
    //开屏广告加载发生超时但是SDK没有及时回调结果的时候，做的一层保护。
    private final WeakHandler mHandler = new WeakHandler(this);
    //开屏广告加载超时时间,建议大于3000,这里为了冷启动第一次加载到广告并且展示,示例设置了3000ms
    private static final int AD_TIME_OUT = 3000;
    private static final int MSG_GO_MAIN = 1;
    //开屏广告是否已经加载
    private boolean mHasLoaded;
    private FrameLayout mSplashContainer; //加载广告的父布局
    private String current_channel = "";

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_splash2);
        StatusBarUtil.setTranslucentForImageView(this, findViewById(R.id.view_need_offset01));

        if (SharedPreferencesUtil.getInstance(this).getSP(CURRENT_CHANNEL)!=null){
            current_channel =  SharedPreferencesUtil.getInstance(this).getSP(CURRENT_CHANNEL);
            Log.i(TAG, "current_channel===" + current_channel);
        }


        mSplashContainer = (FrameLayout) findViewById(R.id.splash_container);

        jumpMainActivity();
//        checkNetwork(SplashActivity.this);//检查联网状态，不联网不进入主页

//        if (SharedPreferencesUtil.getInstance(SplashActivity.this).isSP(Constant.SP_XIEYI)) {
//            mSplashContainer.setVisibility(View.VISIBLE);
//            loadSplashAd();
//        } else {
//            mSplashContainer.setVisibility(View.GONE);
//            jumpMainActivity();
//        }

//        loadSplashAd(current_channel);
    }

    @Override
    public void handleMsg(Message msg) {
        if (msg.what == MSG_GO_MAIN) {
            if (!mHasLoaded) {
                Log.i(TAG, "广告超时，跳转到主页" + System.currentTimeMillis());
//                showToast("广告已超时，跳到主页面");
                jumpMainActivity();
            }
        }
    }


//    private void loadSplashAd(String current_channel) {
//        Log.i(TAG, "current_channel===" + current_channel);
//        if (current_channel ==null|| current_channel.length() ==0)return;
//        String post_id ;
//        switch (current_channel){
//            case "dev":
//                post_id = Constant.CSJ_POSTID_SPLASH;
//                break;
//            default:
//                post_id = "";
//                break;
//        }
//        Log.i(TAG, "post_id===" + post_id);
//        if (post_id == null || post_id.length() ==0)return;
//        Log.i(TAG, "加载开屏广告" + System.currentTimeMillis());
//        mTTAdNative = TTAdManagerHolder.get().createAdNative(this);
//        mHandler.sendEmptyMessageDelayed(MSG_GO_MAIN, AD_TIME_OUT);
//        //step3:创建开屏广告请求参数AdSlot,具体参数含义参考文档
//        AdSlot adSlot = new AdSlot.Builder()
////                .setCodeId(Constant.CSJ_POSTID_SPLASH)
//                .setCodeId(post_id)
//                .setSupportDeepLink(true)
//                .setImageAcceptedSize(1080, 1920)
//                .build();
//        //step4:请求广告，调用开屏广告异步请求接口，对请求回调的广告作渲染处理
//        mTTAdNative.loadSplashAd(adSlot, new TTAdNative.SplashAdListener() {
//            @Override
//            @MainThread
//            public void onError(int code, String message) {
//                Log.i(TAG, message);
//                mHasLoaded = true;
//                Log.i(TAG, "广告 onError" + System.currentTimeMillis());
////                showToast(message);  //去掉广告sdk的弹窗提示
//                jumpMainActivity();
//            }
//
//            @Override
//            @MainThread
//            public void onTimeout() {
//                mHasLoaded = true;
//                Log.i(TAG, "广告 onTimeout" + System.currentTimeMillis());
////                showToast("开屏广告加载超时");
//                jumpMainActivity();
//            }
//
//            @Override
//            @MainThread
//            public void onSplashAdLoad(TTSplashAd ad) {
//                Log.i(TAG, "开屏广告请求成功" + System.currentTimeMillis());
//                mHasLoaded = true;
//                mHandler.removeCallbacksAndMessages(null);
//                if (ad == null) {
//                    return;
//                }
//                //获取SplashView
//                View view = ad.getSplashView();
//                if (view != null) {
//                    mSplashContainer.removeAllViews();
//                    //把SplashView 添加到ViewGroup中,注意开屏广告view：width >=70%屏幕宽；height >=50%屏幕宽
//                    mSplashContainer.addView(view);
//                    //设置不开启开屏广告倒计时功能以及不显示跳过按钮,如果这么设置，您需要自定义倒计时逻辑
//                    //ad.setNotAllowSdkCountdown();
//                } else {
//                    Log.i(TAG, "广告 onSplashAdLoad ,获取广告为空" + System.currentTimeMillis());
//                    jumpMainActivity();
//                }
//                //设置SplashView的交互监听器
//                ad.setSplashInteractionListener(new TTSplashAd.AdInteractionListener() {
//                    @Override
//                    public void onAdClicked(View view, int type) {
//                        Log.i(TAG, "onAdClicked" + System.currentTimeMillis());
////                        showToast("开屏广告点击");
//                    }
//
//                    @Override
//                    public void onAdShow(View view, int type) {
//                        Log.i(TAG, "onAdShow" + System.currentTimeMillis());
////                        showToast("开屏广告展示");
//                    }
//
//                    @Override
//                    public void onAdSkip() {
//                        Log.i(TAG, "onAdSkip" + System.currentTimeMillis());
////                        showToast("开屏广告跳过");
//                        jumpMainActivity();
//                    }
//
//                    @Override
//                    public void onAdTimeOver() {
//                        Log.i(TAG, "onAdTimeOver" + System.currentTimeMillis());
////                        showToast("开屏广告倒计时结束");
//                        jumpMainActivity();
//                    }
//                });
//                if (ad.getInteractionType() == TTAdConstant.INTERACTION_TYPE_DOWNLOAD) {
//                    ad.setDownloadListener(new TTAppDownloadListener() {
//                        boolean hasShow = false;
//
//                        @Override
//                        public void onIdle() {
//                        }
//
//                        @Override
//                        public void onDownloadActive(long totalBytes, long currBytes, String fileName, String appName) {
//                            if (!hasShow) {
//                                Toast.makeText(SplashActivity.this, "下载中...", Toast.LENGTH_SHORT).show();
//                                hasShow = true;
//                            }
//                        }
//
//                        @Override
//                        public void onDownloadPaused(long totalBytes, long currBytes, String fileName, String appName) {
////                            showToast("下载暂停...");
//                        }
//
//                        @Override
//                        public void onDownloadFailed(long totalBytes, long currBytes, String fileName, String appName) {
////                            showToast("下载失败...");
//                        }
//
//                        @Override
//                        public void onDownloadFinished(long totalBytes, String fileName, String appName) {
//                        }
//
//                        @Override
//                        public void onInstalled(String fileName, String appName) {
//                        }
//                    });
//                }
//            }
//        }, AD_TIME_OUT);
//    }

    public static void checkNetwork(Activity activity) {
        if (!NetWorkUtils.isNetConnected()) {
            Log.d("无网络", "网络异常，请检查手机网络状态");
            Toast.makeText(activity, "网络异常，请检查手机网络状态", Toast.LENGTH_SHORT).show();
            return;
        }

    }


    private int hasJump = 0;

    protected void jumpMainActivity() {
        mSplashContainer.postDelayed(new Runnable() {
            @Override
            public void run() {
                startActivity(new Intent(SplashActivity.this, MainActivity.class));
                finish();
            }
        },2000);
    }


//    protected void jumpMainActivity() {
//        Log.i(TAG, "jumpMainActivity" + System.currentTimeMillis());
//        if (hasJump == 0) {
//            Log.i(TAG, "jumpMainActivity 真正执行跳转===" + System.currentTimeMillis());
//            hasJump = 1;
//            startActivity(new Intent(SplashActivity.this, MainActivity.class));
//            finish();
////            overridePendingTransition(0, 0);//去掉跳转动画，但还是会先显示启动页背景才跳转
////            mSplashContainer.removeAllViews();
//        }
//    }

    @Override
    public void onResume() {
        super.onResume();
        MobclickAgent.onPageStart("SplashActivity");//统计页面
        MobclickAgent.onResume(this);
    }

    @Override
    public void onPause() {
        super.onPause();
        MobclickAgent.onPageEnd("SplashActivity");//统计页面
        MobclickAgent.onPause(this);
    }

}
